#include "ClientSocket.h"


Client::Client(CActiveSocket *aSocket)
	: mSocket(aSocket)
{

}


Client::~Client(void)
{
	mSocket->Close();
	delete mSocket;
}

int Client::Send(string Value)
{
	return SendBinary(Value.c_str(), Value.length());
}

int Client::SendBinary(const char * buffer, unsigned int Size)
{
	if(mSocket != nullptr)
	{
		int Return = 0;
		while(Size > 0)
		{
			Return = mSocket->Send((const unsigned char*)buffer, Size);
			if(Return == -1)
			{
				cout << "Unable to SendBinary, error: " << mSocket->GetSocketError() << endl;
				break;
			}
			if(Return == 0)
			{
				cout << "Unable to SendBinary, shutdown" << endl;
				break;
			}
			Size -= Return;
			cout << "Sent " << Return << endl;
		}
		cout << "SendBinary return: " << Return << " | Error?: " << mSocket->GetSocketError() << endl;
		return Return;
	}
	else
	{
		cout << "Socket failure in send, time to give up" << endl;
		return 0;
	}
}

string Client::Receive()
{
	if(mSocket != nullptr)
	{
		int Result;
		string Buffer;
		int Size = 0;
		do
		{
			Result = mSocket->Receive(1024);

			if(Result == -1)
			{
				Buffer = "-1";
				break;
			}
			else if(Result == 0)
			{
				Buffer = "-2";
				break;
			}
			else
			{
				Buffer.append(string((const char*)mSocket->GetData(), Result));
			}
		} while(Result == 1024);
		return Buffer;
	}
	else
	{
		cout << "Socket failure in receive, time to give up?" << endl;
		return "";
	}
}